package frame;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.LoggerFactory;
import com.sun.media.jfxmedia.logging.Logger;
import functions.ems_process_service.Psc;
import javax.servlet.http.HttpServletRequest;

public class HttpHelper {
  private static org.slf4j.Logger logger = LoggerFactory.getLogger(HttpHelper.class);
	private static String UTF8 = "UTF-8";
	private static RequestConfig requestConfig;
    public static boolean isOk = false;
	
	public static String post(Map<String, String> header, Map<String, String> params, String url) throws Exception {
		HttpPost post = null;
		post = new HttpPost(url);
		if (header != null) {
			for (String key : header.keySet()) {
				post.addHeader(key, header.get(key));
			}
		}
		if (params != null) {
			List<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
			post.setConfig(getRequestConfig());
			for (String key : params.keySet()) {
				list.add(new BasicNameValuePair(key, params.get(key)));
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, UTF8);
			post.setEntity(entity);
		}
	
		
	
		String result = HttpClientHelper.getHttpClient().execute(post);
		isOk = HttpClientHelper.isOk;
		return 	result;
	}

	/**
	 * 获取当前审批人
	 * @param header
	 * @param params
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String postAdminUser(Map<String, String> header, String params, String url) throws Exception {
		HttpPost post = null;
		url = FrameWork.getBaseUrl()+url;
		post = new HttpPost(url);
		if (header != null) {
			for (String key : header.keySet()) {
				post.addHeader(key, header.get(key));
			}
		}
		if (params != null) {
			if (params.isEmpty()) {
				throw new Exception("param不能为空！");
			}
			HttpEntity entity = new StringEntity(params, "UTF-8");
			post.setEntity(entity);
		}
		String responseDatas = HttpClientHelper.getHttpClient().execute(post);

		isOk = HttpClientHelper.isOk;

		return responseDatas;
	}

	public static String post(String jsonObject, String url) throws Exception {
		if(url.startsWith("http")) {
			
		}else {
			
			url = FrameWork.getBaseUrl()+url;
		}
		//System.out.println("access to url ----" + url);
		HttpPost post = null;
		post = new HttpPost(url);
		post.addHeader("Content-Type", "application/json;charset=UTF-8");
		if (FrameWork.getCrcToken() != null) {
			post.addHeader("crctoken", FrameWork.getCrcToken());
			logger.info("crcToken : " + FrameWork.getCrcToken());
		}
		if (jsonObject != null) {
			if (jsonObject.isEmpty()) {
			//	throw new Exception("jsonObject不能为空！");
			}
			HttpEntity entity = new StringEntity(jsonObject, "UTF-8");
			post.setEntity(entity);
		}

		String responseDatas = HttpClientHelper.getHttpClient().execute(post);
		isOk = HttpClientHelper.isOk;
		return responseDatas;
	}

	public static String get( Map<String, String> params, String url) throws Exception {
		
		url = FrameWork.getBaseUrl()+url;
		// System.out.println("get ----" + url);
		HttpGet post = null;
		if (params != null) {
			url = url + "?";
			Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
			ArrayList<String> keys = new ArrayList<String>();
			ArrayList<String> values = new ArrayList<String>();
			while (it.hasNext()) {
				Map.Entry<String, String> entry = it.next();
				// System.out.println("key= " + entry.getKey() + entry.getValue());

				keys.add(entry.getKey());
				values.add(entry.getValue());
			}
			for (int i = 0; i < keys.size(); i++) {
				String key = keys.get(i);
				if (i < (keys.size() - 1)) {
					url = url + "key= " + keys.get(i) + params.get(key) + "&";
				} else {
					url = url + "key= " + keys.get(i) + params.get(key);
				}
			}
		}
		post = new HttpGet(url);
		post.addHeader("Content-Type", "application/json;charset=UTF-8");
		if (FrameWork.getCrcToken() != null) {
		    //System.out.println(FrameWork.getCrcToken());
			post.addHeader("crctoken", FrameWork.getCrcToken());
		}

		String responseDatas = HttpClientHelper.getHttpClient().execute(post);
		isOk = HttpClientHelper.isOk;
		return responseDatas;
	}

	public static String post(Map<String, String> params, String url) throws Exception {
		HttpPost post = null;
		url = FrameWork.getBaseUrl()+url;
		post = new HttpPost(url);
		List<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
		post.setConfig(getRequestConfig());
		for (String key : params.keySet()) {
			list.add(new BasicNameValuePair(key, params.get(key)));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, UTF8);
		post.setEntity(entity);
		String result = HttpClientHelper.getHttpClient().execute(post);
		isOk = HttpClientHelper.isOk;
		return result;
	}

	public static RequestConfig getRequestConfig() {
		if (requestConfig == null) {
			requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000).setConnectTimeout(20000)
					.setSocketTimeout(20000).build();
		}
		return requestConfig;
	}

	public static String getClientIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client_IP");
		}
		if (ip == null || ip.length() == 0 || "unkonwn".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip.length() < 5) {
			ip = "0.0.0.0";
		}
		return ip;
	}
}
